package Java7_Concurrency_Cookbook.thread_executor_framework.invoke_any;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ThreadPoolExecutor 类的 invokeAny() 方法接收到一个任务列表, 然后运行任务,
 * 并返回第一个完成任务且没有抛出异常的任务的执行结果.<br/>
 *
 * 某次的运行结果如下:
 * Validator DataBase: Validating a user during 1 seconds
 * Validator LDAP: Validating a user during 9 seconds
 * DataBase: The user has been found
 * Main: Result: DataBase
 * Main: End of the execution
 * LDAP: The user has not been found
 * java.lang.InterruptedException: sleep interrupted
 *      at java.lang.Thread.sleep(Native Method)
 *      ...
 *
 * 经过多次运行, 得出结论如下:
 * 如果A线程优先运行并且找到了正确的结果, B线程会被中断
 * @author lixiangke
 * @date 2017/11/17
 */
public class Main {
    public static void main(String[] args) {
        String username = "java_concurrent_programing_art";
        String password = "java_concurrent_programing_art";
        UserValidator ldapValidator = new UserValidator("LDAP");
        UserValidator dbValidator = new UserValidator("DataBase");
        TaskValidator ldapTask = new TaskValidator(ldapValidator, username, password);
        TaskValidator dbTask = new TaskValidator(dbValidator, username, password);
        List<TaskValidator> taskList = new ArrayList<>();
        taskList.add(ldapTask);
        taskList.add(dbTask);
        ExecutorService executor = Executors.newCachedThreadPool();
        String result;
        try {
            result = executor.invokeAny(taskList);
            System.out.printf("Main: Result: %s\n", result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();
        System.out.printf("Main: End of the execution\n");
    }
}
